/**
 * 每次初始化一个新对象，而不是一个对象，以支持多题同答
 */
import sdk from '@/sdk/index'

class QaService{
  constructor(answer){
    this._answer = answer
    this._pageindex=-1
    this._pageId = -1
    this._sections=[]
    this._isLastPage=false
    this._isFirstPage=true
    // pageLoaded? 表示是否在加载页面，加载完成后，设置为true
    this._pageLoaded = false

    // 初始化 一些数据
    this.init()
  }

  get answerId(){
    return this._answer.id
  }
  /**
   * 不可返回 -1
   */
  get pageIndex(){
    return this._pageindex
  }
  get currPage(){
    return this._pageindex + 1
  }
  get totalPage(){
    return this._answer.answerPages.length
  }
  get sections(){
    return this._sections
  }
  get isLastPage(){
    return this._isLastPage
  }
  get isFirstPage(){
    return this._isFirstPage
  }
  get pageLoaded(){
    return this._pageLoaded
  }

  init(){
    // 决定当前页面
    this._pageindex = 0
    if(this._answer.currentPage){
      this._pageindex = this._answer.answerPages.findIndex(ap => ap.id === this._answer.currentPage)
      if(this._pageindex < this._answer.answerPages.length-1)//如果还有下一页，那么当前应该回答下一页！
        this._pageindex++
    }

    this.loadCurrPage()// 只加载当前页面
  }
  nextPage(){
    // 无论如何，先保存当前页面
    this.saveCurrPage(()=>{
      if(!this._isLastPage){
        this._pageindex ++
        this.loadCurrPage()
      }else{
        alert('已经最后一页，可以提交问卷')
      }
    })
  }
  prevPage(){
    // 无论如何，先保存当前页面
    // this.saveCurrPage(()=>{
    //
    // })
    // 向前一页没必要保存
    if(!this._isFirstPage){
      this._pageindex --
      this.loadCurrPage()
    }else{
      alert('已经第一页了，不能再往前了')
    }
  }
  submit(callbackfn){
    if(this._answer.finished){
      alert('答卷已完成')
      return
    }
    // 需要客户端计算分数，有点麻烦！不安全，以后改进
    let scores = []
    this._answer.answerPages.forEach(ap => {
      if(ap.data){
        this._mergeScore(scores,ap.data.scores)
      }
    })
    let data = {
      answerId:this._answer.id
    }
    if(scores.length>0)
      data.data=JSON.stringify({scores:scores})
    // 提交
    sdk.fetch({
      api:'/publics/answer/finish',
      data,
      success:res=>{
        // 寻找报告的ID号
        console.log('----finished:',res)
        if(callbackfn)
          callbackfn(res)
      },
      fail:err=>{
        console.log(err)
      }
    })
  }
  saveCurrPage(callbackfn){
    console.log('看看答案2',this._sections[0].answer)
    // 判断是否必须
    for(let i=0;i<this._sections.length;i++){
      let sec = this._sections[i]
      if(sec.conditions.required && !sec.answer){
        //有必须的题目没有完成
        alert('题目['+sec.topic+']没有完成')
        return
      }
    }
    // 制作answer,如果有策略，也得算策略分
    let scores = this._countPageScore()
    console.log('分数看看:',scores)
    // 组装数据
    let data = {
      answerPageId:this._pageId,
      metadata:JSON.stringify(this._sections),
    }
    if(scores)
      data.data = JSON.stringify({scores:scores})
    sdk.fetch({
      api:'/publics/answerPage/save',
      data,
      success:res=>{
        console.log(res)
        this._answer = res

        if(callbackfn)
          callbackfn(res)
      },
      fail:err=>{
        console.log(err)
      }
    })
  }
  loadCurrPage(){
    this._pageLoaded = false
    // page id
    this._pageId = this._answer.answerPages[this._pageindex].id
    // 解析得到sections
    this._sections = JSON.parse(this._answer.answerPages[this._pageindex].metadata)

    // 检查是否首页
    if(this._pageindex === 0) this._isFirstPage = true
    else this._isFirstPage = false
    // 检查是否最后一页
    if(this._pageindex === (this._answer.answerPages.length - 1)) this._isLastPage = true
    else this._isLastPage = false
    this._pageLoaded = true
  }
  /*-----------------------------------------以下是辅助函数-------------------------------*/
  _countPageScore(){
    if(this._sections && this._sections.length>0){
      let scores = []
      this._sections.forEach(sec=>{
        // options ,不同的问卷答案的方式不同
        switch (sec.type) {
          case 'checkbox':{
            this._countCheckBox(sec,scores)
            break
          }
          case 'radio':{
            this._countRadio(sec,scores)
            break
          }
          default:{

          }
        }
      })
      // 返回分数数组
      return  scores
    }else return null
  }
  _countCheckBox(section,scores){
    // checkbox 有多个大胆
    if(section.answer,section.answer.length>0){
      section.answer.forEach(ak=>{
        let opt = section.options.find(o=>o.key === ak)
        // opt 正常下肯定在

        if(opt.tactics){
          opt.tactics.forEach(t=>{
            let score = scores.find(s=>s.tactic === t)
            if(!score) {
              score = {tactic: t, score: 0}
              scores.push(score)
            }
            score.score += parseInt(opt.point)
          })
        }
      })
    }
  }
  _countRadio(section,scores){
    if(section.answer){
      console.log(section.answer,section.options)
      let opt = section.options.find(o=>o.key === section.answer)
      // opt 正常下肯定在

      if(opt.tactics){
        opt.tactics.forEach(t=>{
          let score = scores.find(s=>s.tactic === t)
          if(!score) {
            score = {tactic: t, score: 0}
            scores.push(score)
          }
          score.score += parseInt(opt.point)
        })
      }
    }
  }
  _mergeScore(arr1,arr2){
    // 把 arr2 合并到 arr1里
    arr2.forEach(a2=>{
      let tmp = arr1.find(a1 => a1.tactic === a2.tactic)
      if(!tmp){
        tmp =  {tactic: a2.tactic, score: 0}
        arr1.push(tmp)
      }
      tmp.score += a2.score
    })
    return arr1
  }
}

function loadAnswer(id,callbackfn) {
  sdk.fetch({
    api:'/publics/answer/begin',
    data:{instanceId:id},
    success:res=>{
      console.log('answer:',res)
      if(callbackfn) callbackfn(new QaService(res))
    },
    fail:err=>{
      console.log(err)
    }
  })
}

function initQa(answer) {
  return new QaService(answer)
}


export default {
  initQa,
  loadAnswer
}
